﻿using Application;
using Infrastructure;
using Infrastructure.Data.Contexts;
using Microsoft.EntityFrameworkCore;
using Shared.Configuration;
using Shared.Crypto;
using Shared.Logging;
using WebApi.Middlewares;
using WebApi.ProgramExtensions;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

//注册配置内容
builder.Services.Configure<DatabaseSettings>(
    builder.Configuration.GetSection(nameof(DatabaseSettings)));

builder.Services.Configure<LoggingSettings>(
    builder.Configuration.GetSection(nameof(LoggingSettings)));

builder.Services.Configure<RabbitMqSettings>(
    builder.Configuration.GetSection(nameof(RabbitMqSettings)));

builder.Services.Configure<RedisSettings>(
    builder.Configuration.GetSection(nameof(RedisSettings)));

//添加依赖
var dbSettings = builder.Configuration
    .GetSection(nameof(DatabaseSettings))
    .Get<DatabaseSettings>()
    ?? throw new InvalidOperationException("Database settings missing.");

var logSettings = builder.Configuration
    .GetSection(nameof(LoggingSettings))
    .Get<LoggingSettings>()
    ?? throw new InvalidOperationException("log settings missing.");

builder.Services.AddDatabaseContext(dbSettings)
    .AddRepository()
    .AddPasswordHashService()
    .AddSwaggerServices()
    .AddLoggingService(logSettings);

//添加mediatR服务
builder.Services.AddMediatRService();
var app = builder.Build();

app.UseMiddleware<GlobalExceptionHandler>();

//自动迁移数据库
using (var scope = app.Services.CreateScope())
{
    /*
    *安装dotnet ef
    * dotnet tool install --global dotnet - ef
    *
    *添加migrations
    * dotnet ef migrations add<提交信息>
    *
    * 更新数据库
         *dotnet ef database update
         */
    var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    dbContext.Database.Migrate();
}

//添加swagger ui
app.UseSwaggerIfDevelopment(builder.Environment)
   .UseCors("AllowFrontend")
   .UseHttpsRedirection()
   .UseAuthorization();
app.MapControllers();

app.Run();